import pyodbc
import json

from config import config
def exec_query(statement):
    driver = config.dbConfig['driver']

    if 'MySQL' in driver:
        conn = pyodbc.connect(
            f'DRIVER={{MySQL ODBC 8.0 Unicode Driver}};SERVER={config.dbConfig["server"]};PORT={config.dbConfig["port"]};DATABASE={config.dbConfig["database"]};UID={config.dbConfig["username"]};PWD={config.dbConfig["password"]}')
    elif 'SQL Server' in driver:
        conn = pyodbc.connect(
            'DRIVER={SQL Server};SERVER={config.dbConfig["server"]};PORT={config.dbConfig["port"]};DATABASE={config.dbConfig["database"]};UID={config.dbConfig["username"]};PWD={config.dbConfig["password"]}')

    cursor = conn.cursor()
    cursor.execute(statement)

    if 'MySQL' in driver:
        rows = cursor.fetchall()
        results = rows
    else:
        rows = cursor.fetchall()
        columns = [column[0] for column in cursor.description]
        results = []
        for row in rows:
            results.append(dict(zip(columns, row)))

    cursor.close()
    conn.close()

    return json.dumps(results)
